#!/usr/bin/python

###
# Write messages to your most recently active 'mesg y' terminal
#
# $Id: write.py 18 2009-01-25 23:03:36Z eoghan.gaffney $
###


import os, pwd, utmp, time, stat


class writer:
	def __init__(self):
		self.username = pwd.getpwuid(os.getuid())[0]
		
	
	def write(self, message, tty = None):
		if tty == None:
			# If we're explicitly given a tty, write to it.
			# Otherwise, go find the most recently active one.
			tty = self.get_least_idle()
		
		try:
			fd = open(tty, "w")
		except IOError:
			print "Can't open tty %s" % tty
		else:
			# Write a bell character, followed by our message. Beep!
			fd.write("\a\n%s\n" % message)
			
			fd.close()
 
 		
	def get_least_idle(self):
		ut = utmp.UtmpRecord()
		
		# (tty, idletime)
		least_idle_tty = (None, None)
		
		while True:
			# Loop through each entry in utmp
			entry = ut.getutent()
		
			if not entry:
				# Break when we've read through all utmp entries
				break
			
			if entry[0] == utmp.USER_PROCESS:
				# We only want user entries
				if entry[4] == self.username:
					tty = entry[2]

					tty = "/dev/" + tty
			
					try:
						# Stat the file, find its idle time
						ttystat = os.stat(tty)
						idletime = int(time.time() - ttystat[ 7 ])
		
						# 0 if it's mesg n.
						mesg = ttystat[ 0 ] & stat.S_IWGRP
					except OSError:
						print "%s: Not a tty for user %s" % (tty, user)
		
					if mesg:
						if least_idle_tty[1] == None or least_idle_tty[1] > idletime:
							# We either haven't come across a tty, or the tty is idler than this one
							least_idle_tty = (tty, idletime)
					
		if least_idle_tty == (None, None):
			print "Woah, can't find a mesg y tty for %s" % self.username
			return None
		
		return least_idle_tty[0]

if __name__ == "__main__":
	w = writer()

	w.write("Hello! This is a message!")
